import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { renderAndSendMsg } from './xr/xr.js';

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 数据存储目录及文件
const DATA_DIR = path.resolve(__dirname, '../data/mc');
const SUBSCRIPTIONS_FILE = path.join(DATA_DIR, 'mctj.json');
const BG_IMAGES_DIR = path.resolve(__dirname, '../data/背景图');
const BG_IMAGES_FILE = path.join(BG_IMAGES_DIR, 'square_images.json');

// 确保数据目录存在
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR);
if (!fs.existsSync(SUBSCRIPTIONS_FILE)) fs.writeFileSync(SUBSCRIPTIONS_FILE, JSON.stringify({}));
if (!fs.existsSync(BG_IMAGES_DIR)) fs.mkdirSync(BG_IMAGES_DIR);
if (!fs.existsSync(BG_IMAGES_FILE)) fs.writeFileSync(BG_IMAGES_FILE, JSON.stringify([]));

// 获取某个日期的本地日期字符串，格式为 YYYY-MM-DD
function getFormattedDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

class ServerStatusPlugin extends plugin {
  constructor() {
    super({
      name: 'server_status',
      dsc: '服务器状态插件',
      event: 'message',
      priority: 500,
      rule: [
        { reg: "^m今日数据$", fnc: 'displayTodayStats', permission: 'all' },
        { reg: "^m7日数据$", fnc: 'display7DayStats', permission: 'all' }
      ],
    });
  }

  // 显示今天的服务器数据
  async displayTodayStats(e) {
    const subscriptions = this.loadSubscriptions();
    const serverInfo = Object.values(subscriptions).find(s => s.subscribedGroups.includes(e.group_id));

    if (!serverInfo) {
      return e.reply('当前群未订阅任何服务器，请先订阅一个服务器。', true, { recallMsg: 10 });
    }

    const currentDate = getFormattedDate(new Date());
    const activeStats = serverInfo.activeStats[currentDate];

    if (!activeStats) {
      return e.reply('今天还没有统计数据，无法显示。', true, { recallMsg: 10 });
    }

    // 获取今天的数据并按小时显示
    const todayStats = activeStats.split(',').map(Number);
    const hourLabels = [
      '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
      '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
      '12:00', '13:00', '14:00', '15:00', '16:00', '17:00',
      '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'
    ];

    let statsMessage = `服务器活跃玩家统计：${serverInfo.server}\n═════════════════════════\n`;
    statsMessage += '| 时间 / 时间  | 在线玩家数 / 在线玩家数 |\n';
    statsMessage += '──────────────────────────────\n';

    // 每两小时显示一行，时间段对齐
    for (let i = 0; i < 24; i += 2) {
      const firstHour = hourLabels[i].padEnd(8, ' ');
      const secondHour = hourLabels[i + 1].padEnd(8, ' ');
      const firstHourPlayers = todayStats[i] || 0;
      const secondHourPlayers = todayStats[i + 1] || 0;

      statsMessage += `| ${firstHour} / ${secondHour} | ` +
                      `${this.buildPlayerBar(firstHourPlayers)} ${String(firstHourPlayers).padStart(3, ' ')} / ` +
                      `${this.buildPlayerBar(secondHourPlayers)} ${String(secondHourPlayers).padStart(3, ' ')} |\n`;
    }

    statsMessage += '──────────────────────────────\n感谢您的使用！🎮\n═════════════════════════\n';

    const imageUrl = this.getRandomBackgroundImage();
    await renderAndSendMsg(e, imageUrl, statsMessage, '服务器在线数据');
  }

  // 显示过去 7 天的每日最高人数
  async display7DayStats(e) {
    const subscriptions = this.loadSubscriptions();
    const serverInfo = Object.values(subscriptions).find(s => s.subscribedGroups.includes(e.group_id));

    if (!serverInfo) {
      return e.reply('当前群未订阅任何服务器，请先订阅一个服务器。', true, { recallMsg: 10 });
    }

    const activeStats = serverInfo.activeStats;
    const last7Days = Array.from({ length: 7 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - i);
      return getFormattedDate(date);
    });

    let statsMessage = `服务器过去 7 天最高在线统计：${serverInfo.server}\n═════════════════════════\n`;
    statsMessage += '| 日期        | 最高时间  | 在线人数 |\n';
    statsMessage += '──────────────────────────────\n';

    last7Days.forEach(date => {
      const stats = activeStats[date];
      if (stats) {
        const dailyStats = stats.split(',').map(Number);
        const maxPlayers = Math.max(...dailyStats);
        const maxHourIndex = dailyStats.indexOf(maxPlayers);
        const maxHour = `${String(maxHourIndex).padStart(2, '0')}:00`;

        statsMessage += `| ${date} | ${maxHour.padEnd(8, ' ')} | ${String(maxPlayers).padStart(3, ' ')} |\n`;
      } else {
        statsMessage += `| ${date} | 无数据     |     0 |\n`;
      }
    });

    statsMessage += '──────────────────────────────\n感谢您的使用！🎮\n═════════════════════════\n';

    const imageUrl = this.getRandomBackgroundImage();
    await renderAndSendMsg(e, imageUrl, statsMessage, '过去 7 天在线数据');
  }

  // 获取随机背景图片
  getRandomBackgroundImage() {
    const backgroundImages = this.loadBackgroundImages();
    if (backgroundImages.length === 0) {
      return 'https://krseoul.imgtbl.com/i/2024/07/21/669d24f593308.jpeg';
    }
    const randomIndex = Math.floor(Math.random() * backgroundImages.length);
    return backgroundImages[randomIndex];
  }

  // 获取玩家数的表示条形图
  buildPlayerBar(playerCount) {
    if (playerCount < 5) return '*';
    if (playerCount < 10) return '**';
    if (playerCount < 15) return '***';
    if (playerCount < 20) return '****';
    return '*****';
  }

  // 加载订阅数据
  loadSubscriptions() {
    try {
      const data = fs.readFileSync(SUBSCRIPTIONS_FILE, 'utf-8');
      return JSON.parse(data);
    } catch (error) {
      console.error('加载订阅数据失败:', error);
      return {};
    }
  }

  // 加载背景图链接
  loadBackgroundImages() {
    try {
      const data = fs.readFileSync(BG_IMAGES_FILE, 'utf-8');
      return JSON.parse(data);
    } catch (error) {
      console.error('加载背景图链接失败:', error);
      return [];
    }
  }
}

export default ServerStatusPlugin;
